package hqu.cst.xah.service.imp;


import hqu.cst.xah.mapper.ProductMapper;
import hqu.cst.xah.pojo.Product;
import hqu.cst.xah.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductServiceImp implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    //检索产品的情况
    private Product getProductIfExists(Long id,String msg ){
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new RuntimeException(msg + product.getId());
        }
        return product;
    }


    @Override
    public List<Product> getAllProducts() {
        return productMapper.selectList(null);
    }

    @Override
    public Product getProductById(Long id) {
        return  getProductIfExists(id,"产品不存在: ");
    }

    @Override
    public void insertProduct(Product product) {
        Product exist = productMapper.selectById(product.getId());
        if (exist == null) {
            productMapper.insert(product);
        }else{
            throw new RuntimeException("产品已经存在" + product.getId());
        }

    }

    @Override
    public void updateProduct(Product product) {
        getProductIfExists(product.getId(),"产品不存在，无法更新: ");
        productMapper.updateById(product);

    }

    @Override
    public void deleteProduct(Long id) {
        getProductIfExists(id, "产品不存在，无法删除: ");
        productMapper.deleteById(id);
    }
}
